package com.wenjie.plugin.util;

import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * USB设备工具
 */
public class UsbDeviceUtil {

    /**
     * 获取所有的USB设备
     */
    public static void getAllUsbDevice() {
        final Global global = Global.getInstance();
        final Context context = global.getContext();

        UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();

        List<UsbDevice> targetList = new ArrayList<>();

        if (deviceList != null) {
            targetList.addAll(deviceList.values());
        }

        global.setUsbDeviceList(targetList);
    }

    /**
     * 添加USB设备
     */
    public static void addUsbDevice(UsbDevice usbDevice) {
        final Global global = Global.getInstance();

        // 判断是否包含该设备，如果包含则不处理
        List<UsbDevice> usbDeviceList = global.getUsbDeviceList();
        if (usbDeviceList == null) {
            usbDeviceList = new ArrayList<>();
        }

        long count = usbDeviceList.stream().filter(item -> Objects.equals(item.getDeviceId(), usbDevice.getDeviceId())).count();

        if (count > 0) {
            return;
        }

        usbDeviceList.add(usbDevice);

        global.setUsbDeviceList(usbDeviceList);
    }

    /**
     * 移除USB设备
     */
    public static void removeUsbDevice(UsbDevice usbDevice) {
        final Global global = Global.getInstance();

        List<UsbDevice> usbDeviceList = global.getUsbDeviceList();
        if (usbDeviceList == null) {
            usbDeviceList = new ArrayList<>();
        }

        List<UsbDevice> targetList = new ArrayList<>();

        for (UsbDevice device : usbDeviceList) {
            if (!Objects.equals(device.getDeviceId(), usbDevice.getDeviceId())) {
                targetList.add(device);
            }
        }

        global.setUsbDeviceList(targetList);
    }
}
